﻿using System;
using System.Linq;
using CourseManager.Model.Exception;
using CourseManager.Model.Util;

namespace CourseManager.Model.Data
{
	public class UserDAO
	{
		/// <param name="roleType">角色类别</param>
		public static void Add(string id, string password, RoleType roleType)
		{
			DBEntity ent = new DBEntity();
			ent.AddToTab_User(new Tab_User
			                  	{
			                  		userId = id,
			                  		password = CMUtils.EncodeMD5(password),
			                  		type = (int) roleType
			                  	});
			ent.SaveChanges();
		}

		public static void Remove(string id)
		{
			DBEntity ent = new DBEntity();

			Tab_User user = (from _user in ent.Tab_User
			                 where _user.userId.Equals(id)
			                 select _user).FirstOrDefault();

			if (user != null)
			{
				ent.DeleteObject(user);
				ent.SaveChanges();
			}
			
		}

		public static Tab_User FindById(String id)
		{
			DBEntity ent = new DBEntity();

			Tab_User user = (from _user in ent.Tab_User
			                 where _user.userId.Equals(id)
			                 select _user).FirstOrDefault();

			return user;
		}

		public static void ResetPassword(string id)
		{
			SetPassword(id, id);
		}

		public static void SetPassword(string id, string password)
		{
			DBEntity ent = new DBEntity();

			Tab_User user = (from _user in ent.Tab_User
							 where _user.userId.Equals(id)
							 select _user).FirstOrDefault();
			user.password = CMUtils.EncodeMD5(password);
			ent.SaveChanges();
		}
	}
}